package com.aftersale.demo.service.impl;

import com.aftersale.demo.entity.Project;
import com.aftersale.demo.utils.JwtUtil;
import com.aftersale.demo.utils.RedisCache;
import com.aftersale.demo.entity.LoginUser;
import com.aftersale.demo.entity.Result;
import com.aftersale.demo.entity.User;
import com.aftersale.demo.mapper.UserMapper;
import com.aftersale.demo.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
*@Author  空
*@Date    2023/10/23 20:01
*@Desc    用户登录注册服务层
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    UserMapper userMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public Result register(User user) {
        String realVerifyCode=redisCache.getCacheObject(user.getEmail());
        //判断该账户下是否真的有验证码
         if(!Objects.isNull(userMapper.exits(user))){
            return Result.error("409","用户名已存在");
         }else if(realVerifyCode==null){
             return Result.error("401","验证码未发送或已过期");
         }else if(!realVerifyCode.equals(user.getVerifyCode())){
             return Result.error("401","验证码错误");
         }else{
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userMapper.register(user);
            return Result.success("注册成功");
        }



    }

    @Override
    public Result login(User user) {
        //根据用户名密码认证，并将用户名密码封装到authentication对象中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        /*经过一系列接口调用，最终到UserDetails接口查询用户信息,
        *对比UserDtails和authentication中密码并将UserDtails中用户权限封装到Authentication里
         */
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJwt(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        String remind="";
        if(loginUser.getUser().getRemind()){
            if(loginUser.getUser().getRoleId()==2){
                remind="您有待查看的问题";
            }else if(loginUser.getUser().getRoleId()==3){
                remind="您的问题已被解决";
            }
        }
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>(5);
        map.put("token",jwt);
        map.put("userId",userId);
        map.put("role",loginUser.getUser().getRoleId().toString());
        map.put("remind",remind);
        return new Result("200","登录成功",map);
    }

    @Override
    public Result logout() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer userId = loginUser.getUser().getId();
        //删除redis中的值
        redisCache.deleteObject("login:"+userId);
        return Result.success();
    }

    @Override
    public Result reSet(User user) {
        // 账号存在校验
        userMapper.exits(user);
        if(Objects.isNull(user)){
            return Result.error("401","用户名不存在");
        }
        //用户名存在，根据用户名拿出redis中验证码进行比对
        String realVerifyCode=redisCache.getCacheObject(user.getUserName());
        //判断该账户下是否真的有验证码
        if(realVerifyCode==null){
            return Result.error("401","验证码未发送或已过期");
        }else if(!realVerifyCode.equals(user.getVerifyCode())){
            return Result.error("401","验证码错误");
        }else{
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userMapper.forget(user);
            redisCache.deleteObject(user.getUserName());
            return Result.success("修改成功");
        }
    }

    @Override
    public Result getUser(int pageNumber,int pageSize) {
        Page<User> userPage=userMapper.getUser(new Page<>(pageNumber,pageSize));
        return Result.success("请求成功",userPage);
    }

    @Override
    public Result addUser(User user) {
        if(!Objects.isNull(userMapper.exits(user))){
            return Result.error("409","用户名已存在");
        }else{
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userMapper.register(user);
            return Result.success("添加成功");
        }
    }

    @Override
    public Result deleteUser(int id) {
        int num=userMapper.deleteById(id);
        if(num==1){
            return Result.success("删除成功");
        }else{
            return Result.error("401","删除失败，用户不存在或已删除");
        }
    }

    @Override
    public Result updateUser(User user) {
        User dbUser=userMapper.selectById(user.getId());
        if(!user.getUserName().equals(dbUser.getUserName())&&!Objects.isNull(userMapper.exits(user))){
            return Result.error("409","用户名已存在");
        }
        int num=userMapper.updateById(user);
        if(num==1){
            return Result.success("修改成功");
        }else{
            return Result.error("401","修改失败，用户不存在");
        }
    }

    @Override
    public Result myInfo(HttpServletRequest request) {

        int userId=-1;
        String token = request.getHeader("token");
        try {
            Claims claims = JwtUtil.parseJwt(token);
            userId = Integer.parseInt(claims.getSubject());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(userId!=-1){
            User user=userMapper.selectById(userId);
            user.setPassword(null);
            return Result.success("查询成功",user);
        }else{
            return Result.error("401","用户未登录");
        }
    }

    @Override
    public Result updateInfo(User user) {
        if(user.getUserName().equals(userMapper.selectById(user.getId()).getUserName())||Objects.isNull(userMapper.exits(user))){
            userMapper.updateInfo(user);
            return Result.success("修改成功");
        }else {
            return Result.error("409","用户名已存在");
        }
    }
//$2a$12$c2Sr/uy88pQhDkzKhWF4weyjg6rNpatnAQzyoFBXnGN4jv6.KwiBq
//$2a$12$c2Sr/uy88pQhDkzKhWF4weyjg6rNpatnAQzyoFBXnGN4jv6.KwiBq
    @Override
    public Result updatePassword(User user) {
        if(passwordEncoder.matches(user.getOldPassword(),userMapper.selectById(user.getId()).getPassword())){
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userMapper.updatePassword(user);
            return Result.success("修改成功");
        }else {
            return Result.error("401","原密码错误");
        }

    }

    @Override
    public Result getUserProject(int userId, Integer pageNum, Integer pageSize) {
        Page<Project> projects=userMapper.getUserProject(userId,new Page<>(pageNum,pageSize));
        return Result.success(projects);
    }

    @Override
    public Result deleteUserProject(int userId, int projectId) {
        userMapper.deleteproject(userId,projectId);
        return Result.success("删除成功");
    }

    @Override
    public Result addUserProject(int userId, int projectId) {
        if(!Objects.isNull(userMapper.haveProject(userId,projectId))){
            return Result.error("401","用户已拥有此项目");
        }else{
            userMapper.addUserProject(userId,projectId);
        }
        return Result.success("添加成功");
    }

    @Override
    public Result selectUser(String userName,Integer pageNum, Integer pageSize) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("user_name",userName);
        Page<User> userPage=page(new Page<>(pageNum,pageSize),queryWrapper);
        return Result.success(userPage);
    }

    @Override
    public Result selectUserProject(String name, int userId, Integer pageNum, Integer pageSize) {
        Page<Project> projects=userMapper.selectUserProject(userId,name,new Page<>(pageNum,pageSize));
        return Result.success(projects);
    }
}




